package com.gxa.insurance.service.impl;

import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.mapper.CityMapper;
import com.gxa.insurance.pojo.City;
import com.gxa.insurance.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Min
 */
@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityMapper mapper;

    @Transactional()
    @Override
    public Boolean addCity(String cityName) throws BusinessException {
        // 先从数据库中查找是否已存在
        City dbCity=mapper.selectCityByName(cityName);
        if(dbCity!=null){
            throw new BusinessException(ExceptionCode.DUPLICATE_CITY);
        }
        City city = new City();
        city.setCity(cityName);
        // 插入城市
        mapper.insertCity(city);
        return true;
    }

    @Override
    public List<City> selectAllName() {
        List<String> names = new ArrayList<>();

        List<City> cities=mapper.selectAllName();
        // 拿出所有城市的名字
//        for (int i = 0; i < cities.size(); i++) {
//            names.add(cities.get(i).getCity());
//        }

        return cities;
    }

    @Override
    public Boolean deleteCityById(Integer id) {
        mapper.deleteCityById(id);
        return true;
    }

    @Override
    public Map<String,Object> selectAllCity(Integer page, Integer pageSize) {
        if(page==null || page<=0){
            page=1;
        }
        if(pageSize==null || pageSize<=0){
            pageSize=10;
        }
        page=(page-1)*pageSize;

        List<City> cities = mapper.selectAllCity(page,pageSize);
        Integer count=mapper.selectCount();
        Map<String, Object> map = new HashMap<>();
        map.put("list",cities);
        map.put("count",count);
        return map;
    }
}
